package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzService  clazzService;

    @Override
    public PageResult<Student> getpageResult(StudentQueryParam param) {
        //获取分页参数
        Page<Student> page = Page.of(param.getPage(), param.getPageSize());
        //进行分页条件查询
        page = lambdaQuery()
                .like(param.getName() != null && !param.getName().isEmpty(),Student::getName, param.getName())
                .eq(param.getDegree() != null,Student::getDegree,  param.getDegree())
                .eq(param.getClazzId() != null,Student::getClazzId,  param.getClazzId())
                .orderByDesc(Student::getUpdateTime)
                .page(page);
        //获取学员查询结果
        List<Student> studentList = page.getRecords();
        if (! studentList.isEmpty()){
            HashSet<Integer> clazzIds = (HashSet<Integer>)studentList.stream().map(Student::getClazzId).collect(Collectors.toSet());
            if (! clazzIds.isEmpty()){
                List<Clazz> clazzes = clazzService.listByIds(clazzIds);
                Map<Integer, String> clazzName = clazzes.stream().collect(Collectors.toMap(Clazz::getId, Clazz::getName));
                studentList.forEach(student -> student.setClazzName(clazzName.get(student.getClazzId())));
            }
        }

        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    public void violation(Integer id, Integer score) {
        Student student = getById(id);
        student.setViolationCount((short)(student.getViolationCount() + 1));
        student.setViolationScore((short)(student.getViolationScore() + score));
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }

    /**
     * 新增学生
     * @param student
     */
    @Override
    public void saveStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        save(student);
    }
    /**
     * 修改学生
     * @param student
     */
    @Override
    public void updateStudentById(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }
}
